package cn.lblbc.webbrowser.utils

import android.content.Context
import android.os.Environment
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 完成的下载管理器
 * 用于保存和获取自定义下载器完成的下载项
 */
class CompletedDownloadManager(private val context: Context) {
    
    /**
     * 保存完成的下载项
     */
    fun saveCompletedDownload(downloadId: Long, fileName: String, filePath: String, fileSize: Long, mimeType: String) {
        try {
            println("【完成下载管理】保存完成的下载: $fileName")
            
            // 获取已有的完成下载列表
            val completedDownloads = getAllCompletedDownloads().toMutableList()
            
            // 创建新的完成下载项
            val completedDownload = CompletedDownload(
                id = downloadId,
                fileName = fileName,
                filePath = filePath,
                fileSize = fileSize,
                mimeType = mimeType,
                timestamp = System.currentTimeMillis()
            )
            
            // 添加到列表
            completedDownloads.add(completedDownload)
            
            // 保存到SharedPreferences
            val sharedPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            val editor = sharedPrefs.edit()
            
            // 将列表转换为JSON字符串
            val json = completedDownloads.joinToString(separator = SEPARATOR) { it.toJsonString() }
            
            // 保存JSON字符串
            editor.putString(COMPLETED_DOWNLOADS_KEY, json)
            editor.apply()
            
            println("【完成下载管理】保存成功，当前完成下载数量: ${completedDownloads.size}")
        } catch (e: Exception) {
            println("【完成下载管理】保存完成下载失败: ${e.message}")
            e.printStackTrace()
        }
    }
    
    /**
     * 获取所有完成的下载项
     */
    fun getAllCompletedDownloads(): List<CompletedDownload> {
        try {
            val sharedPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            val json = sharedPrefs.getString(COMPLETED_DOWNLOADS_KEY, "") ?: ""
            
            if (json.isEmpty()) return emptyList()
            
            // 将JSON字符串转换为完成下载列表
            val completedDownloads = json.split(SEPARATOR).mapNotNull { jsonString ->
                try {
                    val parts = jsonString.split("|")
                    if (parts.size >= 6) {
                        CompletedDownload(
                            id = parts[0].toLong(),
                            fileName = parts[1],
                            filePath = parts[2],
                            fileSize = parts[3].toLong(),
                            mimeType = parts[4],
                            timestamp = parts[5].toLong()
                        )
                    } else {
                        null
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    null
                }
            }
            
            // 过滤掉不存在的文件
            val validDownloads = completedDownloads.filter { 
                val file = File(it.filePath)
                file.exists()
            }
            
            // 如果有不存在的文件，更新保存的列表
            if (validDownloads.size < completedDownloads.size) {
                val sharedPrefsEditor = sharedPrefs.edit()
                val newJson = validDownloads.joinToString(separator = SEPARATOR) { it.toJsonString() }
                sharedPrefsEditor.putString(COMPLETED_DOWNLOADS_KEY, newJson)
                sharedPrefsEditor.apply()
            }
            
            return validDownloads
        } catch (e: Exception) {
            e.printStackTrace()
            return emptyList()
        }
    }
    
    /**
     * 删除完成的下载项
     */
    fun removeCompletedDownload(downloadId: Long) {
        try {
            // 获取已有的完成下载列表
            val completedDownloads = getAllCompletedDownloads().toMutableList()
            
            // 移除指定ID的下载
            completedDownloads.removeAll { it.id == downloadId }
            
            // 保存到SharedPreferences
            val sharedPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            val editor = sharedPrefs.edit()
            
            // 将列表转换为JSON字符串
            val json = completedDownloads.joinToString(separator = SEPARATOR) { it.toJsonString() }
            
            // 保存JSON字符串
            editor.putString(COMPLETED_DOWNLOADS_KEY, json)
            editor.apply()
            
            println("【完成下载管理】删除完成下载: $downloadId")
        } catch (e: Exception) {
            println("【完成下载管理】删除完成下载失败: ${e.message}")
            e.printStackTrace()
        }
    }
    
    /**
     * 删除所有完成的下载项
     */
    fun removeAllCompletedDownloads() {
        try {
            // 保存到SharedPreferences
            val sharedPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            val editor = sharedPrefs.edit()
            
            // 清空完成下载列表
            editor.putString(COMPLETED_DOWNLOADS_KEY, "")
            editor.apply()
            
            println("【完成下载管理】删除所有完成下载")
        } catch (e: Exception) {
            println("【完成下载管理】删除所有完成下载失败: ${e.message}")
            e.printStackTrace()
        }
    }
    
    /**
     * 完成的下载项数据类
     */
    data class CompletedDownload(
        val id: Long,
        val fileName: String,
        val filePath: String,
        val fileSize: Long,
        val mimeType: String,
        val timestamp: Long
    ) {
        /**
         * 将完成的下载项转换为JSON字符串
         */
        fun toJsonString(): String {
            return "$id|$fileName|$filePath|$fileSize|$mimeType|$timestamp"
        }
        
        /**
         * 获取格式化的日期
         */
        fun getFormattedDate(): String {
            val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
            return dateFormat.format(Date(timestamp))
        }
    }
    
    companion object {
        private const val PREFS_NAME = "completed_downloads_prefs"
        private const val COMPLETED_DOWNLOADS_KEY = "completed_downloads"
        private const val SEPARATOR = "###"
    }
}